"""This module provides 发文助手"""

import os
import logging
import platform
import time
import shutil

# from apscheduler.schedulers.blocking import BlockingScheduler
# from apscheduler.triggers.cron import CronTrigger

### 本地目录
from mp3tomp4.push import put_down_phone_myshipinhao
from mp3tomp4.push import auto_push_mp4_kuaisou
from mp3tomp4.push import auto_push_mp4_xiaohongsh
from mp3tomp4.push import auto_push_mp4_zhihu

# from auto.write.csdn import auto_write_csdn
# from auto.write.douyu import atuo_write_douyu
# from auto.write.weibo import auto_write_weibo

LOG_FORMAT = (
    "[%(asctime)s][%(levelname)s][%(filename)s:%(funcName)s:%(lineno)d] %(message)s"
)
DATE_FORMAT = "%Y-%m-%d %H:%M:%S"


def find_mp4_files(directory):
    """获取视频文件"""
    mp4_files = []
    for root, __, files in os.walk(directory):
        for file in files:
            if file.endswith(".mp4"):
                mp4_files.append(os.path.join(root, file))
    return mp4_files


def find_daily_msg(directory_path):
    """每日输出内容 和图片内容"""
    pic_list = []
    content = ""
    for root, _, files in os.walk(directory_path):
        # 文件集合
        for file in files:
            if file.endswith(".png") or file.endswith(".jpg"):
                file_path = os.path.join(root, file)
                pic_list.append(file_path)
            if file.endswith(".txt"):
                file_path = os.path.join(root, file)
                with open(file_path, encoding="UTF-8") as f:
                    print(f"文件 {file_path} 的内容是：")
                    for line in f:
                        # print(line.strip())  # 逐行读取并打印文件内容
                        content += (line.strip()) + "\r\n"
                        print(content)
    print("===================")
    print(content)
    return content, pic_list


def auto_upload_mp4():
    """
    上传视频这个事情消耗很大精力，
    尤其是晚上时候 等待上传时间，到半夜 这个价值千万视频 也不看。
    也不上传。
    虽然很多人上传是容易事情。但是你来说不行，坚决不行。
    """
    print("auto_upload_mp4")
    if platform.system() == "Windows":
        input_path = r"D:\mp4\auto_write\mp4"
        back_path = r"D:\mp4\bak"
    elif platform.system() == "Darwin":
        input_path = r"/Users/wangchuanyi/mp4/input"
        back_path = r"/Users/wangchuanyi/mp4/bak"
    else:
        input_path = r"/root/mp4/output"
        back_path = r"/root/mp4/bak"

    file_list = find_mp4_files(input_path)
    if len(file_list) == 0:
        logging.info("no task")
        print("no task")
        return
    write_msg = get_txt_contents(input_path)
    artile_title = "《掌控习惯》如何养成好习惯并戒除坏习惯"
    artile_content = (
        "《掌控习惯》是一部系统且深入教授人们如何养成好习惯、戒除坏习惯的行动指南书"
    )
    for file in file_list:
        try:
            print(file)
            put_down_phone_myshipinhao.interface_auto_upload_mp4_shipinhao(
                file, artile_title, artile_content
            )
            print("interface_auto_upload_mp4_shipinhao.....")
            time.sleep(3)
            auto_push_mp4_kuaisou.interface_auo_upload_mp4_kuaishou(
                file, artile_title, artile_content
            )
            print("interface_auo_upload_mp4_kuaishou.....")
            time.sleep(3)
            auto_push_mp4_xiaohongsh.interface_auo_upload_mp4_myxiaohongshu(
                file, artile_title, artile_content
            )
            print("interface_auo_upload_mp4_myxiaohongshu.....")
            time.sleep(3)
            auto_push_mp4_zhihu.interface_auo_upload_mp4_zhihu(
                file, artile_title, artile_content
            )
            print("interface_auo_upload_mp4_myxiaohongshu.....")
        finally:
            print("...")
            # 删除文件
            temp = os.path.join(back_path, os.path.basename(file))
            if os.path.exists(temp):
                os.remove(file)
            else:
                shutil.move(file, back_path)
                print(file_list)
                print(back_path)
    time.sleep(1)

    # 遍历目录
    # for root, __, files in os.walk(input_path):
    #     for file in files:
    #         if file.endswith(".mp4"):
    #             file_path = os.path.join(root, file)
    #             # 删除文件
    #             os.remove(file_path)
    #             print(f"已删除文件: {file_path}")


def get_txt_contents(directory_path):
    """
    获取指定目录下所有txt文件的内容。

    参数:
    directory_path (str): 要搜索txt文件的目录路径。

    返回:
    dict: 一个字典，键为文件名，值为文件内容。
    """
    txt_contents = {}
    # 遍历目录下的所有文件
    for filename in os.listdir(directory_path):
        if filename.endswith(".txt"):  # 检查文件扩展名是否为 .txt
            file_path = os.path.join(directory_path, filename)
            with open(file_path, "r", encoding="utf-8") as file:
                txt_contents[filename] = file.read()  # 读取文件内容并存储在字典中
    return txt_contents


###############################################################


def handle_auto_upload_mp4():
    """
    上传视频这个事情消耗很大精力，
    尤其是晚上时候 等待上传时间，到半夜 这个价值千万视频 也不看。
    也不上传。
    虽然很多人上传是容易事情。但是你来说不行，坚决不行。
    """
    local_file_path = r"/Users/wangchuanyi/mp4/book/1.mp4"
    artile_title = "笔记:早起的奇迹"
    artile_content = """
克服赖床方法：睡前积极暗示：期待第二天精力充沛地醒来。
1. 闹钟放远：迫使自己下床。
2. 起床刷牙：醒神。
3. 喝水补水：对抗疲劳。
4. 穿上运动服：为后续活动做准备
#do书 #每天听本书
"""
    try:
        put_down_phone_myshipinhao.interface_auto_upload_mp4_shipinhao(
            local_file_path, artile_title, artile_content
        )
        # print("interface_auto_upload_mp4_shipinhao.....")
        # time.sleep(3)
        auto_push_mp4_kuaisou.interface_auo_upload_mp4_kuaishou(
            local_file_path, artile_title, artile_content
        )
        print("interface_auo_upload_mp4_kuaishou.....")
        time.sleep(3)
        auto_push_mp4_xiaohongsh.interface_auo_upload_mp4_myxiaohongshu(
            local_file_path, artile_title, artile_content
        )
        print("interface_auo_upload_mp4_myxiaohongshu.....")
        time.sleep(3)
        auto_push_mp4_zhihu.interface_auo_upload_mp4_zhihu(
            local_file_path, artile_title, artile_content
        )
        time.sleep(1)
    finally:
        print("...")


def get_txt_contents(directory_path):
    """
    获取指定目录下所有txt文件的内容。

    参数:
    directory_path (str): 要搜索txt文件的目录路径。

    返回:
    dict: 一个字典，键为文件名，值为文件内容。
    """
    txt_contents = {}
    # 遍历目录下的所有文件
    for filename in os.listdir(directory_path):
        if filename.endswith(".txt"):  # 检查文件扩展名是否为 .txt
            file_path = os.path.join(directory_path, filename)
            with open(file_path, "r", encoding="utf-8") as file:
                txt_contents[filename] = file.read()  # 读取文件内容并存储在字典中
    return txt_contents


###############################################################

if __name__ == "__main__":

    # job_defaults = {
    #     'coalesce': False,
    #     'max_instances': 1
    # }
    handle_auto_upload_mp4()

    # 4点:开始上传文件
    # backsched.add_job(auto_upload_mp4, CronTrigger.from_crontab("0 7 * * *"), id="put_small_file")
    # print("start pythonTryEverythingWin")
    # backsched.start()
